<template>
  <div class="sheepfarm-list-container">
    <!-- 顶部标题栏 -->
    <div class="page-header">
      <span class="page-title">羊场设置</span>
    </div>
    <!-- 查询条件区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :inline="true" :model="queryInfo" class="search-form">
        <el-form-item label="羊场全称：">
          <el-input v-model="queryInfo.FarmName" placeholder="请输入羊场全称" clearable style="width: 200px;" />
        </el-form-item>
        <el-form-item label="负责人：">
          <el-input v-model="queryInfo.Manager" placeholder="请输入负责人" clearable style="width: 200px;" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="openAddDialog">新增</el-button>
          <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">批量删除</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addDialogVisible" title="羊场设置-新增" width="500px" :close-on-click-modal="false">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="110px" label-position="right">
        <el-form-item label="羊场全称" prop="FarmName" required>
          <el-input v-model="addForm.FarmName" placeholder="请输入羊场全称" />
        </el-form-item>
        <el-form-item label="羊场简称" prop="FarmShortName" required>
          <el-input v-model="addForm.FarmShortName" placeholder="请输入羊场简称" />
        </el-form-item>
        <el-form-item label="羊场规模" prop="TheScaleOfSheepfarmId" required>
          <el-select v-model="addForm.TheScaleOfSheepfarmId" placeholder="请选择羊场规模" style="width: 100%">
            <el-option v-for="item in scaleOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="建账日期" prop="CreateDate" required>
          <el-date-picker v-model="addForm.CreateDate" type="date" placeholder="请选择建账日期" style="width: 100%" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="负责人" prop="Manager" required>
          <el-input v-model="addForm.Manager" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="详细地址" prop="Address" required>
          <el-input v-model="addForm.Address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="管理部门" prop="Department">
          <el-input v-model="addForm.Department" placeholder="请输入管理部门" />
        </el-form-item>
        <el-form-item label="是否启用" prop="Status">
          <el-radio-group v-model="addForm.Status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleAddSubmit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" title="羊场设置-编辑" width="500px" :close-on-click-modal="false">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="110px" label-position="right">
        <el-form-item label="羊场全称" prop="FarmName" required>
          <el-input v-model="editForm.FarmName" placeholder="请输入羊场全称" />
        </el-form-item>
        <el-form-item label="羊场简称" prop="FarmShortName" required>
          <el-input v-model="editForm.FarmShortName" placeholder="请输入羊场简称" />
        </el-form-item>
        <el-form-item label="羊场规模" prop="TheScaleOfSheepfarmId" required>
          <el-select v-model="editForm.TheScaleOfSheepfarmId" placeholder="请选择羊场规模" style="width: 100%">
            <el-option v-for="item in scaleOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="建账日期" prop="CreateDate" required>
          <el-date-picker v-model="editForm.CreateDate" type="date" placeholder="请选择建账日期" style="width: 100%" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="负责人" prop="Manager" required>
          <el-input v-model="editForm.Manager" placeholder="请输入负责人" />
        </el-form-item>
        <el-form-item label="详细地址" prop="Address" required>
          <el-input v-model="editForm.Address" placeholder="请输入详细地址" />
        </el-form-item>
        <el-form-item label="管理部门" prop="Department">
          <el-input v-model="editForm.Department" placeholder="请输入管理部门" />
        </el-form-item>
        <el-form-item label="是否启用" prop="Status">
          <el-radio-group v-model="editForm.Status">
            <el-radio :label="true">启用</el-radio>
            <el-radio :label="false">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="handleEditSubmit">保存</el-button>
      </template>
    </el-dialog>


    






    <!-- 表格区域 -->
    <el-card class="table-card" shadow="never">
      <el-table 
        :data="tableData" 
        border 
        stripe 
        v-loading="loading" 
        style="width: 100%;" 
        :header-cell-style="centerStyle" 
        :cell-style="centerStyle"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50" align="center" header-align="center" />
        <el-table-column type="index" label="序号" width="60" align="center" header-align="center" />
        <el-table-column prop="FarmCode" label="羊场编码" width="130" align="center" header-align="center" />
        <el-table-column prop="FarmName" label="羊场全称" width="150" align="center" header-align="center" />
        <el-table-column prop="FarmShortName" label="羊场简称" width="120" align="center" header-align="center" />
        <el-table-column prop="ThescalethsheepName" label="规模" width="110" align="center" header-align="center" />
        <el-table-column prop="CreateDate" label="建账日期" width="160" align="center" header-align="center">
          <template #default="scope">
            {{ formatDate(scope.row.CreateDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="Manager" label="负责人" width="100" align="center" header-align="center" />
        <el-table-column prop="Address" label="详细地址" width="150" align="center" header-align="center" />
        <el-table-column prop="Department" label="管理部门" width="120" align="center" header-align="center" />
        <el-table-column prop="Status" label="状态" width="80" align="center" header-align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.Status ? 'success' : 'info'"
              style="cursor: pointer"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.Status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="Creator" label="创建人" width="100" align="center" header-align="center" />
        <el-table-column prop="CreateTime" label="创建时间" width="180" align="center" header-align="center">
          <template #default="scope">
            {{ formatDate(scope.row.CreateTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="Modifier" label="修改人" width="100" align="center" header-align="center" />
        <el-table-column prop="ModifyTime" label="修改时间" width="180" align="center" header-align="center">
          <template #default="scope">
            {{ formatDate(scope.row.ModifyTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="140" align="center" header-align="center">
          <template #default="scope">
            <el-tooltip
              content="禁用状态下无法操作"
              placement="top"
              :disabled="scope.row.Status"
            >
              <span>
                <el-button
                  type="primary"
                  size="small"
                  text
                  @click="openEditDialog(scope.row)"
                  :disabled="!scope.row.Status"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="small"
                  text
                  @click="handleDeleteSheepfarm(scope.row)"
                  :disabled="!scope.row.Status"
                >删除</el-button>
              </span>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="pagination-bar">
        <el-pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :page-size="queryInfo.PageSize"
          :current-page="queryInfo.PageIndex"
          :page-sizes="[10, 15, 20, 50, 100]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Sheep_BreedingRead, Sheep_BreedingWrite } from '@/utils/Interceptors'

interface SheepfarmRow {
  SheepfarmId: number;
  FarmName: string;
  FarmCode: string;
  FarmShortName: string;
  TheScaleOfSheepfarmId: string | number;
  CreateDate: string;
  Manager: string;
  Address: string;
  Department: string;
  Status: boolean;
  Creator: string;
  CreateTime: string;
  Modifier: string;
  ModifyTime: string;
  IsDelete: boolean;
}

// 查询条件和分页信息
const queryInfo = reactive({
  FarmName: '',
  Manager: '',
  PageIndex: 1,
  PageSize: 20
})

const tableData = ref<any[]>([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref<SheepfarmRow[]>([])

// 新增弹窗相关
const addDialogVisible = ref(false)
const addFormRef = ref()
const addForm = reactive({
  FarmCode: '',
  FarmName: '',
  FarmShortName: '',
  TheScaleOfSheepfarmId: '',
  CreateDate: '',
  Manager: '',
  Address: '',
  Department: '',
  Creator: '',
  Status: true
})
const addRules = {
  FarmName: [{ required: true, message: '请输入羊场全称', trigger: 'blur' }],
  FarmShortName: [{ required: true, message: '请输入羊场简称', trigger: 'blur' }],
  TheScaleOfSheepfarmId: [{ required: true, message: '请选择羊场规模', trigger: 'change' }],
  CreateDate: [{ required: true, message: '请选择建账日期', trigger: 'change' }],
  Manager: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  Address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

// 编辑弹窗相关
const editDialogVisible = ref(false)
const editFormRef = ref()
const editForm = reactive({
  SheepfarmId: 0,
  FarmCode: '',
  FarmName: '',
  FarmShortName: '',
  TheScaleOfSheepfarmId: '',
  CreateDate: '',
  Manager: '',
  Address: '',
  Department: '',
  Status: true,
  Creator: '',
  CreateTime: '',
  Modifier: '',
  ModifyTime: '',
  IsDelete: false
})
const editRules = {
  FarmName: [{ required: true, message: '请输入羊场全称', trigger: 'blur' }],
  FarmShortName: [{ required: true, message: '请输入羊场简称', trigger: 'blur' }],
  TheScaleOfSheepfarmId: [{ required: true, message: '请选择羊场规模', trigger: 'change' }],
  CreateDate: [{ required: true, message: '请选择建账日期', trigger: 'change' }],
  Manager: [{ required: true, message: '请输入负责人', trigger: 'blur' }],
  Address: [{ required: true, message: '请输入详细地址', trigger: 'blur' }]
}

const scaleOptions = ref<any[]>([])

async function fetchScaleOptions() {
  try {
    const { data } = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchSheepFiles')
    if (data.code === 200 && Array.isArray(data.data)) {
      scaleOptions.value = data.data.filter((item: any) => !item.IsDelete).map((item: any) => ({
        value: item.ThescalethsheepfarmId,
        label: item.ThescalethsheepName
      }))
    } else {
      scaleOptions.value = []
    }
  } catch {
    scaleOptions.value = []
  }
}

function openAddDialog() {
  const userInfoStr = localStorage.getItem('userInfo')
  let creator = ''
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      creator = userInfo.UserName || ''
    } catch {}
  }
  Object.assign(addForm, {
    FarmCode: Date.now().toString(),
    FarmName: '',
    FarmShortName: '',
    TheScaleOfSheepfarmId: '',
    CreateDate: '',
    Manager: '',
    Address: '',
    Department: '',
    Creator: creator,
    Status: true
  })
  fetchScaleOptions()
  addDialogVisible.value = true
}

async function handleAddSubmit() {
  if (!addFormRef.value) return
  await addFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    // 构造参数
    const params = {
      FarmCode: addForm.FarmCode,
      FarmName: addForm.FarmName,
      FarmShortName: addForm.FarmShortName,
      TheScaleOfSheepfarmId: addForm.TheScaleOfSheepfarmId,
      CreateDate: addForm.CreateDate,
      Manager: addForm.Manager,
      Address: addForm.Address,
      Department: addForm.Department,
      Creator: addForm.Creator
    }
    try {
      const { data } = await Sheep_BreedingWrite.post('/api/Sheepfarm/CreateSheepfarm', params)
      if (data.code === 200) {
        ElMessage.success('新增成功')
        addDialogVisible.value = false
        getSheepfarmList()
      } else {
        ElMessage.error(data.msg || '新增失败')
      }
    } catch (e) {
      ElMessage.error('请求失败')
    }
  })
}

// 打开编辑弹窗
function openEditDialog(row: any) {
  const userInfoStr = localStorage.getItem('userInfo')
  let modifier = ''
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      modifier = userInfo.UserName || ''
    } catch {}
  }
  
  // 复制数据到编辑表单
  Object.assign(editForm, {
    SheepfarmId: row.SheepfarmId,
    FarmCode: row.FarmCode,
    FarmName: row.FarmName,
    FarmShortName: row.FarmShortName,
    TheScaleOfSheepfarmId: row.TheScaleOfSheepfarmId,
    CreateDate: row.CreateDate ? row.CreateDate.split('T')[0] : '',
    Manager: row.Manager,
    Address: row.Address,
    Department: row.Department,
    Status: row.Status,
    Creator: row.Creator,
    CreateTime: row.CreateTime,
    Modifier: modifier,
    ModifyTime: new Date().toISOString(),
    IsDelete: false
  })
  
  fetchScaleOptions()
  editDialogVisible.value = true
}

// 编辑提交
async function handleEditSubmit() {
  if (!editFormRef.value) return
  await editFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    
    // 构造参数
    const params = {
      SheepfarmId: editForm.SheepfarmId,
      FarmCode: editForm.FarmCode,
      FarmName: editForm.FarmName,
      FarmShortName: editForm.FarmShortName,
      TheScaleOfSheepfarmId: editForm.TheScaleOfSheepfarmId,
      CreateDate: editForm.CreateDate,
      Manager: editForm.Manager,
      Address: editForm.Address,
      Department: editForm.Department,
      Status: editForm.Status,
      Creator: editForm.Creator,
      CreateTime: editForm.CreateTime,
      Modifier: editForm.Modifier,
      ModifyTime: editForm.ModifyTime,
      IsDelete: editForm.IsDelete
    }
    
    try {
      const { data } = await Sheep_BreedingWrite.put('/api/Sheepfarm/UpdateSheepfarm', params)
      if (data.code === 200) {
        ElMessage.success('修改羊场信息成功')
        editDialogVisible.value = false
        getSheepfarmList()
      } else {
        ElMessage.error(data.msg || '修改失败')
      }
    } catch (e) {
      ElMessage.error('请求失败')
    }
  })
}

// 删除羊场
function handleDeleteSheepfarm(row: any) {
  ElMessageBox.confirm(
    `确定要删除羊场 “${row.FarmName}” 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const { data } = await Sheep_BreedingWrite.delete('/api/Sheepfarm/DeleteSheepfarm', { data: { SheepfarmId: row.SheepfarmId } })
      if (data.code === 200) {
        ElMessage.success('删除成功')
        getSheepfarmList()
      } else {
        ElMessage.error(data.msg || '删除失败')
      }
    } catch (e) {
      ElMessage.error('请求失败')
    }
  }).catch(() => {})
}

// 批量删除
async function handleBatchDelete() {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的羊场')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 个羊场吗？`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )

    const params = {
      SheepfarmIds: selectedRows.value.map(row => row.SheepfarmId)
    }

    const res = await Sheep_BreedingWrite.delete('/api/Sheepfarm/BatchDeleteSheepfarms', { data: params })

    if (res.data.code === 200) {
      ElMessage.success('批量删除成功')
      selectedRows.value = []
      getSheepfarmList()
    } else {
      ElMessage.error(res.data.msg || '批量删除失败')
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('操作失败')
    }
  }
}

// 切换启用/禁用状态
async function handleStatusChange(row: SheepfarmRow) {
  try {
    const newStatus = !row.Status;
    const confirmText = `确定要${newStatus ? '启用' : '禁用'}羊场"${row.FarmName}"吗？`;
    
    await ElMessageBox.confirm(
      confirmText,
      '状态修改确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const params = {
      SheepfarmId: row.SheepfarmId,
      Status: newStatus
    };

    const res = await Sheep_BreedingWrite.put('/api/Sheepfarm/UpdateSheepfarmStatus', params);

    if (res.data.code === 200) {
      ElMessage.success(`${newStatus ? '启用' : '禁用'}成功`);
      getSheepfarmList();
    } else {
      ElMessage.error(res.data.msg || '操作失败');
    }
  } catch (err) {
    if (err !== 'cancel') {
      ElMessage.error('操作失败');
    }
  }
}

// 居中样式
const centerStyle = () => ({ textAlign: 'center' })

// 格式化日期
function formatDate(val: string) {
  if (!val) return ''
  return val.length > 10 ? val.slice(0, 19).replace('T', ' ') : val
}

// 获取羊场列表
const getSheepfarmList = async () => {
  loading.value = true
  try {
    const { data } = await Sheep_BreedingRead.get('/api/Sheepfarm/SearchSheepfarm_management', {
      params: {
        FarmName: queryInfo.FarmName,
        Manager: queryInfo.Manager,
        PageIndex: queryInfo.PageIndex,
        PageSize: queryInfo.PageSize
      }
    })
    if (data.code === 200) {
      tableData.value = data.PageData || []
      total.value = data.TotalCount || 0
    } else {
      tableData.value = []
      total.value = 0
      ElMessage.error(data.msg || '查询失败')
    }
  } catch (e) {
    tableData.value = []
    total.value = 0
    ElMessage.error('请求失败')
  }
  loading.value = false
}

// 查询按钮
const handleQuery = () => {
  queryInfo.PageIndex = 1
  getSheepfarmList()
}
// 重置按钮
const handleReset = () => {
  queryInfo.FarmName = ''
  queryInfo.Manager = ''
  queryInfo.PageIndex = 1
  getSheepfarmList()
}
// 分页：每页条数变化
const handleSizeChange = (size: number) => {
  queryInfo.PageSize = size
  queryInfo.PageIndex = 1
  getSheepfarmList()
}
// 分页：页码变化
const handleCurrentChange = (page: number) => {
  queryInfo.PageIndex = page
  getSheepfarmList()
}

// 表格多选变化
function handleSelectionChange(selection: SheepfarmRow[]) {
  selectedRows.value = selection
}

onMounted(() => {
  getSheepfarmList()
})
</script>

<style scoped>
.sheepfarm-list-container {
  padding: 32px 0 0 0;
  min-height: 100vh;
  background: #f6f8fa;
}
.page-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0 0 18px 32px;
}
.page-title {
  font-size: 20px;
  font-weight: bold;
  color: #222;
  background: transparent;
  border-radius: 0;
  padding: 0;
  margin-bottom: 0;
  letter-spacing: 2px;
  box-shadow: none;
}
.search-card {
  margin: 0 auto 18px auto;
  border-radius: 16px;
  max-width: 1200px;
  box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.06);
}
.table-card {
  min-height: 400px;
  border-radius: 16px;
  max-width: 1200px;
  margin: 0 auto;
  box-shadow: 0 2px 12px 0 rgba(64, 158, 255, 0.06);
}
.pagination-bar {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>